package com.collect.senegal.zhiScene.zhiCollection.zhiBigGroup.zhiPerformance;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.collect.senegal.R;
import com.collect.senegal.zhiAdater.zhiLevelDetail.ZHILevelDetailMergeAmount;
import com.collect.senegal.zhiAdater.zhiLevelDetail.ZHILevelDetailMergeOrder;
import com.collect.senegal.zhiBase.BaseFragment;
import com.collect.senegal.zhiBean.zhiReceive.ZHIRGroupBonusEntity;
import com.collect.senegal.zhiBean.zhiReceive.ZHIRGroupPerformanceMoneyEntity;
import com.collect.senegal.zhiBean.zhiReceive.ZHIRGroupUserEntity;
import com.collect.senegal.zhiBean.zhiReceive.ZHIRGroupUserPerformanceMergeEntity;
import com.collect.senegal.zhiBean.zhiSend.ZHISPerfermanceEntity;
import com.collect.senegal.zhiBean.zhiSend.ZHISendEntity;
import com.collect.senegal.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.senegal.zhiHelper.ZHIMainProcessHelper;
import com.collect.senegal.zhiScene.zhiCollection.zhiAdmin.zhiSort.ZHIAdminCompareByAmountASC;
import com.collect.senegal.zhiScene.zhiCollection.zhiAdmin.zhiSort.ZHIAdminCompareByAmountDES;
import com.collect.senegal.zhiScene.zhiCollection.zhiBigGroup.zhiRoot.ZHIRootBigGroupFragmentInterface;
import com.collect.senegal.zhiScene.zhiCollection.zhiGroup.zhiPerformance.zhiSort.ZHIGroupOrderCompareByRateASC;
import com.collect.senegal.zhiScene.zhiCollection.zhiGroup.zhiPerformance.zhiSort.ZHIGroupOrderCompareByRateDES;
import com.collect.senegal.zhiUtils.StringUtil;
import com.collect.senegal.zhiUtils.ZHICalendarUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;

import butterknife.BindView;

@SuppressLint("NonConstantResourceId")
public class ZHIPerformanceBigGroupOrderFragment extends BaseFragment<ZHIPerformanceBigGroupPresenter> implements ZHIPerformanceBigGroupContract.View {

    @BindView(R.id.srl_swipe_layout)
    SwipeRefreshLayout srl_swipe_layout;

    @BindView(R.id.tv_page_title)
    TextView tv_page_title;

    @BindView(R.id.tv_group_user)
    TextView tv_group_user;

    @BindView(R.id.ll_level_bg_order)
    LinearLayout ll_level_bg_order;
    @BindView(R.id.ll_detail_bg_order)
    LinearLayout ll_detail_bg_order;
    @BindView(R.id.tv_total_orders_num)
    TextView tv_total_orders_num;
    @BindView(R.id.tv_total_collected_num)
    TextView tv_total_collected_num;
    @BindView(R.id.tv_total_collected_rate)
    TextView tv_total_collected_rate;
    @BindView(R.id.rc_detail_list_order)
    RecyclerView rc_detail_list_order;

    @BindView(R.id.ll_level_bg_amount)
    LinearLayout ll_level_bg_amount;
    @BindView(R.id.ll_detail_bg_amount)
    LinearLayout ll_detail_bg_amount;
    @BindView(R.id.tv_total_collected_amount)
    TextView tv_total_collected_amount;
    @BindView(R.id.rc_detail_list_amount)
    RecyclerView rc_detail_list_amount;

    @BindView(R.id.iv_sort)
    ImageView iv_sort;

    @BindView(R.id.iv_note)
    ImageView iv_note;
    @BindView(R.id.iv_filter)
    ImageView iv_filter;

    private PopupMenu mPopupMenuUser;
    private ArrayList<ZHIRGroupUserEntity> mGourpUserNameList;
    private ZHIRGroupUserEntity mCurSysLoginUser;

    private final ZHILevelDetailMergeOrder mZHILevelDetailMergeOrder = new ZHILevelDetailMergeOrder();
    private final ZHILevelDetailMergeAmount mZHILevelDetailMergeAmount = new ZHILevelDetailMergeAmount();

    private ArrayList<ZHIRGroupUserPerformanceMergeEntity> mGroupUserPerformanceMergeEntityArrayList;
    private ArrayList<ZHIRGroupPerformanceMoneyEntity> mGroupPerformanceMoneyEntityArrayList;

    /**
     * 是否为降序
     */
    private boolean mIsArraySortDesNow = true;

    private ZHIRootBigGroupFragmentInterface mZHIRootBigGroupFragmentInterface;

    @Override
    protected void initInjector() {
        mFragmentComponent.inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_perfermance_big_group_order;
    }

    @Override
    protected void initView(View view) {
        try {
            srl_swipe_layout.setColorSchemeColors(getResources().getColor(R.color.theme_color_0));
            srl_swipe_layout.setOnRefreshListener(() -> refreshData(false));

            tv_page_title.setOnClickListener(v -> {
            });

            iv_note.setOnClickListener(v -> ZHIProjectRouter.toPerformanceColloectionBonusRules());

            iv_sort.setOnClickListener(v -> {
                if (ll_level_bg_amount.getVisibility() == View.VISIBLE) {
                    if (mGroupPerformanceMoneyEntityArrayList != null) {
                        if (mIsArraySortDesNow) {
                            Collections.sort(mGroupPerformanceMoneyEntityArrayList, new ZHIAdminCompareByAmountASC());
                            mZHILevelDetailMergeAmount.notifyDataSetChanged();
                            mIsArraySortDesNow = false;
                        } else {
                            Collections.sort(mGroupPerformanceMoneyEntityArrayList, new ZHIAdminCompareByAmountDES());
                            mZHILevelDetailMergeAmount.notifyDataSetChanged();
                            mIsArraySortDesNow = true;
                        }
                    }
                } else if(ll_level_bg_order.getVisibility() == View.VISIBLE) {
                    if (mGroupUserPerformanceMergeEntityArrayList != null) {
                        if (mIsArraySortDesNow) {
                            Collections.sort(mGroupUserPerformanceMergeEntityArrayList, new ZHIGroupOrderCompareByRateASC());
                            mZHILevelDetailMergeOrder.notifyDataSetChanged();
                            mIsArraySortDesNow = false;
                        } else {
                            Collections.sort(mGroupUserPerformanceMergeEntityArrayList, new ZHIGroupOrderCompareByRateDES());
                            mZHILevelDetailMergeOrder.notifyDataSetChanged();
                            mIsArraySortDesNow = true;
                        }
                    }
                }
            });

            iv_filter.setOnClickListener(v -> {
                if (mGourpUserNameList == null || mGourpUserNameList.size() == 0) {
                    if (mPresenter != null) {
                        mPresenter.getBigGroupUsers(getActivity(), false, new ZHISendEntity());
                    }
                } else {
                    showPopMenuViewApp(iv_filter);
                }
            });

            initEvent();

            if (mPresenter != null) {
                mPresenter.getBigGroupUsers(getActivity(), true, new ZHISendEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mZHIRootBigGroupFragmentInterface = (ZHIRootBigGroupFragmentInterface) activity;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onGetErrorInfo() {
        srl_swipe_layout.setRefreshing(false);
    }

    @Override
    public void onGetGroupUserPerformanceOrderMerge(ArrayList<ZHIRGroupUserPerformanceMergeEntity> zhirGroupUserPerformanceMergeEntityArrayList, ZHISPerfermanceEntity zhisPerfermanceEntity) {
        try {
            srl_swipe_layout.setRefreshing(false);

            ///////////////////////
            BigDecimal totalNumDecimal = new BigDecimal("0");
            for (int i = 0; i < zhirGroupUserPerformanceMergeEntityArrayList.size(); i++) {
                ZHIRGroupUserPerformanceMergeEntity zhirGroupUserPerformanceMergeEntity = zhirGroupUserPerformanceMergeEntityArrayList.get(i);
                BigDecimal bigDecimal = zhirGroupUserPerformanceMergeEntity.getTotalNumBigDecimal();
                totalNumDecimal = totalNumDecimal.add(bigDecimal);
            }
            tv_total_orders_num.setText(StringUtil.numberFormatter00(totalNumDecimal.stripTrailingZeros().toPlainString()));

            ///////////////////////
            int settledNum = 0;
            for (int i = 0; i < zhirGroupUserPerformanceMergeEntityArrayList.size(); i++) {
                ZHIRGroupUserPerformanceMergeEntity zhirGroupUserPerformanceMergeEntity = zhirGroupUserPerformanceMergeEntityArrayList.get(i);
                settledNum += zhirGroupUserPerformanceMergeEntity.getTodaySettledNumFormat();
            }
            tv_total_collected_num.setText(StringUtil.numberFormatter00(String.valueOf(settledNum)));

            ///////////////////////
            String collectRateStr = "0";
            if (totalNumDecimal.intValue() > 0) {
                float totalNumL = totalNumDecimal.floatValue();
                float settledNumL = settledNum * 1.0F;
                float collectRateL = settledNumL / totalNumL;
                collectRateStr = StringUtil.numberFormatterThousandPercent(collectRateL + "");
            }
            tv_total_collected_rate.setText(collectRateStr);

            ///////////////////////
            for (int i = 0; i < zhirGroupUserPerformanceMergeEntityArrayList.size(); i++) {
                ZHIRGroupUserPerformanceMergeEntity zhirGroupUserPerformanceMergeEntity = zhirGroupUserPerformanceMergeEntityArrayList.get(i);
                zhirGroupUserPerformanceMergeEntity.setEndDate(zhisPerfermanceEntity.getEndDateMonthDayFormat());
                zhirGroupUserPerformanceMergeEntity.setStartDate(zhisPerfermanceEntity.getStartDateMonthDayFormat());
            }
            Collections.sort(zhirGroupUserPerformanceMergeEntityArrayList, new ZHIGroupOrderCompareByRateDES());
            mGroupUserPerformanceMergeEntityArrayList = zhirGroupUserPerformanceMergeEntityArrayList;

            mZHILevelDetailMergeOrder.setNewData(zhirGroupUserPerformanceMergeEntityArrayList);

            ///////////////////////
//            if (mPresenter != null && ZHIProjectConfigs.SHOW_GROUP_BONUS) {
//                mPresenter.getGroupBonus(getActivity(), getCaseBonusParams());
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetGroupUserPerformanceMoneyMerge(ArrayList<ZHIRGroupPerformanceMoneyEntity> zhirGroupPerformanceMoneyEntityArrayList, ZHISPerfermanceEntity zhisPerfermanceEntity) {
        try {
            srl_swipe_layout.setRefreshing(false);

            BigDecimal resultDecimal = new BigDecimal("0");
            for (int i = 0; i < zhirGroupPerformanceMoneyEntityArrayList.size(); i++) {
                ZHIRGroupPerformanceMoneyEntity zhirGroupPerformanceMoneyEntity = zhirGroupPerformanceMoneyEntityArrayList.get(i);
                BigDecimal bigDecimal = zhirGroupPerformanceMoneyEntity.getRepayAmountBigDecimal();
                resultDecimal = resultDecimal.add(bigDecimal);
            }
            tv_total_collected_amount.setText(StringUtil.numberFormatter00(resultDecimal.stripTrailingZeros().toPlainString()));

            ///////////////////////
            for (int i = 0; i < zhirGroupPerformanceMoneyEntityArrayList.size(); i++) {
                ZHIRGroupPerformanceMoneyEntity zhirGroupPerformanceMoneyEntity = zhirGroupPerformanceMoneyEntityArrayList.get(i);
                zhirGroupPerformanceMoneyEntity.setEndDate(zhisPerfermanceEntity.getEndDateMonthDayFormat());
                zhirGroupPerformanceMoneyEntity.setStartDate(zhisPerfermanceEntity.getStartDateMonthDayFormat());
            }
            Collections.sort(zhirGroupPerformanceMoneyEntityArrayList, new ZHIAdminCompareByAmountDES());
            mGroupPerformanceMoneyEntityArrayList = zhirGroupPerformanceMoneyEntityArrayList;

            mZHILevelDetailMergeAmount.setNewData(zhirGroupPerformanceMoneyEntityArrayList);

            ///////////////////////
//            if (mPresenter != null && ZHIProjectConfigs.SHOW_GROUP_BONUS) {
//                mPresenter.getGroupBonus(getActivity(), getCaseBonusParams());
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetGroupUsers(ArrayList<ZHIRGroupUserEntity> zhirGroupUserEntityArrayList) {
        try {
            srl_swipe_layout.setRefreshing(false);

            if (mZHIRootBigGroupFragmentInterface != null) {
                mZHIRootBigGroupFragmentInterface.onReloadGroupUserList();
                mZHIRootBigGroupFragmentInterface.onShowFilterPerformanceOrder();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetGroupBonus(ZHIRGroupBonusEntity zhirGroupBonusEntity, ZHISPerfermanceEntity zhisPerfermanceEntity) {
        try {
            srl_swipe_layout.setRefreshing(false);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetBigGroupUsers(boolean isFirstLoad, ArrayList<ZHIRGroupUserEntity> bigGroupUserList) {
        try {
            srl_swipe_layout.setRefreshing(false);
            mGourpUserNameList = bigGroupUserList;

            if (isFirstLoad) {
                if (bigGroupUserList.size() > 0) {
                    mCurSysLoginUser = bigGroupUserList.get(0);
                    tv_page_title.setText(mCurSysLoginUser.getGroupName());
                    tv_group_user.setText(mCurSysLoginUser.getLoginName());
                    refreshData(true);
                }
                return;
            }

            showPopMenuViewApp(iv_filter);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint({"InflateParams", "SetTextI18n"})
    public void initEvent() {
        srl_swipe_layout.setOnRefreshListener(() -> refreshData(false));

        mZHILevelDetailMergeOrder.setEmptyView(getRefreshEmptyView());
        mZHILevelDetailMergeAmount.setEmptyView(getRefreshEmptyView());

        rc_detail_list_order.setLayoutManager(new GridLayoutManager(this.getActivity(), 1));
        rc_detail_list_order.setAdapter(mZHILevelDetailMergeOrder);

        rc_detail_list_amount.setLayoutManager(new GridLayoutManager(this.getActivity(), 1));
        rc_detail_list_amount.setAdapter(mZHILevelDetailMergeAmount);
    }

    public void initOrderData(boolean showDialog) {
        try {
            ll_level_bg_order.setVisibility(View.VISIBLE);
            ll_detail_bg_order.setVisibility(View.VISIBLE);

            ll_level_bg_amount.setVisibility(View.GONE);
            ll_detail_bg_amount.setVisibility(View.GONE);

            ZHISPerfermanceEntity zhisPerfermanceEntity = getCaseSearchParams();
            if (zhisPerfermanceEntity == null) {
                return;
            }
            if (mPresenter != null) {
                mPresenter.getGroupUserPerformanceOrderMerge(getActivity(), zhisPerfermanceEntity, showDialog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initAmountData(boolean showDialog) {
        try {
            ll_level_bg_order.setVisibility(View.GONE);
            ll_detail_bg_order.setVisibility(View.GONE);

            ll_level_bg_amount.setVisibility(View.VISIBLE);
            ll_detail_bg_amount.setVisibility(View.VISIBLE);

            ZHISPerfermanceEntity zhisPerfermanceEntity = getAmountCaseSearchParams();
            if (zhisPerfermanceEntity == null) {
                return;
            }
            if (mPresenter != null) {
                mPresenter.getGroupUserPerformanceMoneyMerge(getActivity(), zhisPerfermanceEntity, showDialog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void refreshData(boolean showDialog) {
        if (mCurSysLoginUser == null) {
            srl_swipe_layout.setRefreshing(false);
            return;
        }
        //如果是b3以上,显示金额列表
        if (mCurSysLoginUser.getLeven().contains("3")) {
            initAmountData(showDialog);
        } else {
            initOrderData(showDialog);
        }
    }

    private ZHISPerfermanceEntity getCaseSearchParams() {
        if (TextUtils.isEmpty(mCurSysLoginUser.getLoginName())) {
            srl_swipe_layout.setRefreshing(false);
            return null;
        }
        //return mZHIRootBigGroupFragmentInterface.onGetPerfermanceFilterParams();
        ZHISPerfermanceEntity zhisPerfermanceEntity = new ZHISPerfermanceEntity();
        zhisPerfermanceEntity.setSysLoginName(mCurSysLoginUser.getLoginName());
        zhisPerfermanceEntity.setLeven(ZHIMainProcessHelper.getInstance().getLoginEntity().getDefaultLevenApiFormat());
        zhisPerfermanceEntity.setStartDateForDisplay(ZHICalendarUtil.getCurMonthFirstDayFormatString());
        zhisPerfermanceEntity.setEndDateForDisplay(ZHICalendarUtil.getCurMonthCurDayFormatString());
        zhisPerfermanceEntity.setStartDate(ZHICalendarUtil.getCurMonthFirstDayFormatString());
        zhisPerfermanceEntity.setEndDate(ZHICalendarUtil.getDateStringAfterDate(ZHICalendarUtil.getCurMonthCurDayFormatString(), 1));
        zhisPerfermanceEntity.setLeaderUserId(mCurSysLoginUser.getUserId());
        return zhisPerfermanceEntity;
    }

    private ZHISPerfermanceEntity getCaseBonusParams() {
        if (TextUtils.isEmpty(mCurSysLoginUser.getLoginName())) {
            srl_swipe_layout.setRefreshing(false);
            return null;
        }
        ZHISPerfermanceEntity zhisPerfermanceEntity = new ZHISPerfermanceEntity();
        zhisPerfermanceEntity.setSysLoginName(mCurSysLoginUser.getLoginName());
        zhisPerfermanceEntity.setLeven(ZHIMainProcessHelper.getInstance().getLoginEntity().getDefaultLevenApiFormat());
        zhisPerfermanceEntity.setStartDateForDisplay(ZHICalendarUtil.getCurMonthFirstDayFormatString());
        zhisPerfermanceEntity.setEndDateForDisplay(ZHICalendarUtil.getCurMonthCurDayFormatString());
        zhisPerfermanceEntity.setStartDate(ZHICalendarUtil.getCurMonthFirstDayFormatString());
        zhisPerfermanceEntity.setEndDate(ZHICalendarUtil.getDateStringAfterDate(ZHICalendarUtil.getCurMonthCurDayFormatString(), 1));
        zhisPerfermanceEntity.setLeaderUserId(mCurSysLoginUser.getUserId());
        return zhisPerfermanceEntity;
    }


    private ZHISPerfermanceEntity getAmountCaseSearchParams() {
        if (TextUtils.isEmpty(mCurSysLoginUser.getLoginName())) {
            srl_swipe_layout.setRefreshing(false);
            return null;
        }
        ZHISPerfermanceEntity zhisPerfermanceEntity = new ZHISPerfermanceEntity();
        zhisPerfermanceEntity.setSysLoginName(mCurSysLoginUser.getLoginName());
        zhisPerfermanceEntity.setLeven("B+");
        zhisPerfermanceEntity.setStartDateForDisplay(ZHICalendarUtil.getCurMonthFirstDayFormatString());
        zhisPerfermanceEntity.setEndDateForDisplay(ZHICalendarUtil.getCurMonthCurDayFormatString());
        zhisPerfermanceEntity.setStartDate(ZHICalendarUtil.getCurMonthFirstDayFormatString());
        zhisPerfermanceEntity.setEndDate(ZHICalendarUtil.getDateStringAfterDate(ZHICalendarUtil.getCurMonthCurDayFormatString(), 1));
        zhisPerfermanceEntity.setLeaderUserId(mCurSysLoginUser.getUserId());
        return zhisPerfermanceEntity;
    }

    private ZHISPerfermanceEntity getAmountCaseBonusParams() {
        if (TextUtils.isEmpty(mCurSysLoginUser.getLoginName())) {
            srl_swipe_layout.setRefreshing(false);
            return null;
        }
        ZHISPerfermanceEntity zhisPerfermanceEntity = new ZHISPerfermanceEntity();
        zhisPerfermanceEntity.setLeven("B+");
        zhisPerfermanceEntity.setSysLoginName(mCurSysLoginUser.getLoginName());
        zhisPerfermanceEntity.setStartDateForDisplay(ZHICalendarUtil.getCurMonthFirstDayFormatString());
        zhisPerfermanceEntity.setEndDateForDisplay(ZHICalendarUtil.getCurMonthCurDayFormatString());
        zhisPerfermanceEntity.setStartDate(ZHICalendarUtil.getCurMonthFirstDayFormatString());
        zhisPerfermanceEntity.setEndDate(ZHICalendarUtil.getDateStringAfterDate(ZHICalendarUtil.getCurMonthCurDayFormatString(), 1));
        zhisPerfermanceEntity.setLeaderUserId(mCurSysLoginUser.getUserId());
        return zhisPerfermanceEntity;
    }

    private View getRefreshEmptyView() {
        View emptyView = getLayoutInflater().inflate(R.layout.view_empty_no_data, null);
        emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        emptyView.setOnClickListener(v -> refreshData(true));
        return emptyView;
    }

    private void showPopMenuViewApp(View view) {
        if (mPopupMenuUser != null) {
            mPopupMenuUser.dismiss();
            mPopupMenuUser = null;
        }

        if (mGourpUserNameList == null || mGourpUserNameList.size() == 0) {
            return;
        }

        mPopupMenuUser = new PopupMenu(getActivity(), view);
        Menu menu_more = mPopupMenuUser.getMenu();

        for (int i = 0; i < mGourpUserNameList.size(); i++) {
            ZHIRGroupUserEntity zhirGroupUserEntity = mGourpUserNameList.get(i);
            menu_more.add(Menu.NONE, Menu.FIRST + (i + 1), (i + 1), zhirGroupUserEntity.getGroupName());
        }

        mPopupMenuUser.setOnMenuItemClickListener(item -> {
            String menuItem = item.getTitle().toString();
            Log.d(TAG, "mPopupMenuUser: " + menuItem);
            for (int i = 0; i < mGourpUserNameList.size(); i++) {
                ZHIRGroupUserEntity zhirGroupUserEntity = mGourpUserNameList.get(i);
                if (zhirGroupUserEntity.getGroupName().equalsIgnoreCase(menuItem)) {
                    mCurSysLoginUser = zhirGroupUserEntity;
                }
            }
            tv_page_title.setText(mCurSysLoginUser.getGroupName());
            tv_group_user.setText(mCurSysLoginUser.getLoginName());
            refreshData(true);
            return true;
        });

        mPopupMenuUser.show();
    }
}
